from .models import Book, UserInfo
from rest_framework.generics import GenericAPIView, ListAPIView
from rest_framework.response import Response
from .serializers import BookSerializer, UserInfoSerializer, BookssSerializer
from .permission import UsersPermission
from .throttle import MyThrottle
from rest_framework.filters import SearchFilter, OrderingFilter
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin
from rest_framework.pagination import PageNumberPagination

from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework.permissions import IsAuthenticated
from .auth import MyJWTAuthentication, LoginAuthentication,UserInfoJWTAuthentication
from rest_framework.views import APIView


class BookView(GenericAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
    authentication_classes = [UserInfoJWTAuthentication]
    # permission_classes = [IsAuthenticated, ]
    # throttle_classes = [MyThrottle, ]
    # 配置过滤类，至少继承GenericAPIView类
    # filter_backends = [SearchFilter, OrderingFilter]
    # 配置过滤条件,按字段名过滤,可以写多个
    # search_fields = ['title']
    # 分页配置
    pagination_class = PageNumberPagination

    def get(self, request):
        serializer = self.get_serializer(instance=self.get_queryset(), many=True)
        return Response(serializer.data)

    def post(self, request):
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        else:
            return Response(serializer.errors)


class LoginView(GenericAPIView):
    queryset = UserInfo.objects.all()
    serializer_class = UserInfoSerializer
    authentication_classes = []  # 使用了全局认证之后，登陆的接口需要局部配置不使用认证

    def post(self, request):
        # 获取登录用户名密码
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            return Response(serializer.validated_data)
        else:
            return Response(serializer.errors)


from django_filters.rest_framework import DjangoFilterBackend


class BookFilterView(ListAPIView):
    queryset = Book.objects.all()
    serializer_class = BookssSerializer
    # 内置过滤类，排序类
    filter_backends = [SearchFilter, OrderingFilter]
    # 第三方过滤类 django-filter
    # filter_backends = [DjangoFilterBackend, ]
    # filter_fields = ['title']
    search_fields = ['title']

    # ordering_fields = ['id']

    # 分页配置
    pagination_class = PageNumberPagination


from .serializers import UserLoginSerializer


class UserView(GenericAPIView):
    queryset = UserInfo.objects.all()
    serializer_class = UserLoginSerializer

    def post(self, request):
        # 获取登录用户名密码
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            return Response(serializer.validated_data)
        else:
            return Response(serializer.errors)
